// module.exports: 导出函数

module.exports = app => {
	const express = require('express')
	const AdminUser = require('../../models/AdminUser')
	// token检验
	const jwt = require('jsonwebtoken')
	// 错误处理
	const assert = require('http-assert')
	// 登录授权中间件(登录校验)
	const authMiddleware = require('../../middleware/auth')
	// 资源中间件
	const resourceMiddleware = require('../../middleware/resource')
	const router = express.Router({
		mergeParams: true //合并url参数
	})

	// 添加资源
	router.post('/', async (req, res) => {
    const model = await req.Model.create(req.body)
		res.send(model)
	})
	// 资源列表
	router.get('/', async(req, res, next) => {
		const token = String(req.headers.authorization || '').split(' ').pop()
		assert(token, 401, '请先登录')
		const { id } = jwt.verify(token, app.get('secret'))
		assert(id, 401, '请先登录')
		req.user = await AdminUser.findById(id)
		assert(req.user, 401, '请先登录')
		await next()
	}, async (req, res) => {
		const queryOptions = {}
		if (req.Model.modelName === 'Category') {
			queryOptions.populate = 'parent'
		}
		const items = await req.Model.find().setOptions(queryOptions).limit(100)
		res.send(items)
	})
	// 通过id获取资源详情
	router.get('/:id', async (req, res) => {
		const model = await req.Model.findById(req.params.id)
		res.send(model)
	})
	// 修改资源
	router.put('/:id', async (req, res) => {
		const model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
		res.send(model)
	})
	// 删除资源
	router.delete('/:id', async (req, res) => {
		const model = await req.Model.findByIdAndDelete(req.params.id, req.body)
		res.send({
			success: true
		})
	})



	app.use('/admin/api/rest/:resource', authMiddleware(), resourceMiddleware(),  router)

	const multer = require('multer')
	// dest: 图片默认存储地址
	const upload = multer({
		dest: __dirname + '/../../uploads'
	})
	// upload.single('file'): 设置单文件上传
	app.post('/admin/api/upload', authMiddleware(), upload.single('file'), async (req, res) => {
		// 获取前端页面上传的数据
		const file = req.file
		const imgURL = file.filename
		// 返回给前端页面拼接图片路径
		file.url = `http://localhost:3000/uploads/${imgURL}`
		// 返回数据给前端页面
		res.send(file)
	})

	app.post('/admin/api/login', async (req, res) => {
		const {username, password} = req.body
		// 1.根据用户名找用户
		const user = await AdminUser.findOne({ username }).select('+password')
		assert(user, 422, '用户不存在')
		// 2.校验密码
		const isValid = require('bcrypt').compareSync(password, user.password)
		assert(isValid, 422, '密码错误')
		// 3.返回token
		const token = jwt.sign({ id: user._id }, app.get('secret'))
		res.send({ token })
	})

	// 错误处理函数
	app.use(async (err, req, res, next)=> {
		res.status(err.statusCode || 500).send({
			message: err.message
		})
	})
}